package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentApiImpl implements CommentApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserInfoApi userInfoApi;

    //保存评论
    @Override
    public int save(Comment comment) {
        //1. 保存评论
        mongoTemplate.save(comment);

        //2. 对朋友圈的(点赞|评论|喜欢)数量进行+1
        Query query = new Query(Criteria.where("_id").is(comment.getPublishId()));
        Update update = new Update();
        update.inc(comment.getCol(), 1);
        mongoTemplate.updateFirst(query, update, Publish.class);

        //3. 查询当前动态的评论数、点赞数、喜欢数
        Publish publish = mongoTemplate.findById(comment.getPublishId(), Publish.class);

        if (comment.getCommentType() == 1) {
            //点赞
            return publish.getLikeCount();
        } else if (comment.getCommentType() == 2) {
            //评论
            return publish.getCommentCount();
        } else {
            return publish.getLoveCount();
        }
    }

    @Override
    public int delete(Comment comment) {
        //1. 删除评论
        Query commentQuery = new Query(Criteria.where("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType())
                .and("pubType").is(comment.getPubType())
                .and("userId").is(comment.getUserId()));
        mongoTemplate.remove(commentQuery, Comment.class);

        //2. 对朋友圈的(点赞|评论|喜欢)数量进行-1
        Query query = new Query(Criteria.where("_id").is(comment.getPublishId()));
        Update update = new Update();
        update.inc(comment.getCol(), -1);
        mongoTemplate.updateFirst(query, update, Publish.class);

        //3. 查询当前动态的评论数、点赞数、喜欢数
        Publish publish = mongoTemplate.findById(comment.getPublishId(), Publish.class);

        if (comment.getCommentType() == 1) {
            //点赞
            return publish.getLikeCount();
        } else if (comment.getCommentType() == 2) {
            //评论
            return publish.getCommentCount();
        } else {
            return publish.getLoveCount();
        }
    }

    @Override
    public PageResult queryCommentsList(String movementId, Integer page, Integer pagesize) {
        Query query = new Query(Criteria.where("publishId").is(new ObjectId(movementId))
                .and("commentType").is(2)  //1 点赞， 2：评论
                .and("pubType").is(1));  //产品类型：1 朋友圈
        query.with(Sort.by(Sort.Order.desc("created"))).skip((page - 1) * pagesize).limit(pagesize);

        List<Comment> list = mongoTemplate.find(query, Comment.class);
        long counts = mongoTemplate.count(query, Comment.class);


        PageResult pageResult = new PageResult(page, pagesize, (int) counts, list);
        return pageResult;
    }

    /**
     * 获取用户收到的评论列表（分页）
     *
     * @param userId      用户Id
     * @param commentType 评论内容类型：1-对动态操作 2-对视频操作 3-对评论操作
     * @param page
     * @param pageSize
     * @return PageResult<commentVo>
     */
    @Override
    public PageResult getComments(long userId, int commentType, Integer page, Integer pageSize) {
        // 使用userid查找用户的所有发布 获取发布id列表 圈子&视频
        Query publishQuery = new Query(Criteria.where("userId").is(userId));
        List<Publish> publishes = mongoTemplate.find(publishQuery, Publish.class);
        Query videoQuery = new Query(Criteria.where("userId").is(userId));
        List<Video> videos = mongoTemplate.find(videoQuery, Video.class);
        List<ObjectId> publishIdList = new ArrayList<>();
        publishes.forEach(publish -> publishIdList.add(publish.getId()));
        videos.forEach(video -> publishIdList.add(video.getId()));
        // 使用publishId获取用户所有发布的所有评论情况 筛选出所有类型为'commentType'的评论
        Query commentQuery = new Query(Criteria.where("publishId").in(publishIdList));
        commentQuery.addCriteria(Criteria.where("commentType").is(commentType));
        commentQuery.with(Sort.by(Sort.Order.desc("created"))).skip((page - 1) * pageSize).limit(pageSize);
        List<Comment> comments = mongoTemplate.find(commentQuery, Comment.class);
        // 查询总数
        long count = mongoTemplate.count(commentQuery, Comment.class);
        // 封装到commentVo
        ArrayList<CommentVo> voList = new ArrayList<>();
        comments.forEach(comment -> {
            // 使用评论的userId查询对应的user info
            CommentVo commentVo = new CommentVo();
            commentVo.setContent(comment.getContent());
            commentVo.setLikeCount(comment.getLikeCount());
            commentVo.setId(comment.getId().toString());
            commentVo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(comment.getCreated())));
            UserInfo reviewer = userInfoApi.findById(comment.getUserId());
            commentVo.setAvatar(reviewer.getAvatar());
            commentVo.setNickname(reviewer.getNickname());
            voList.add(commentVo);
        });
        return new PageResult(page, pageSize, (int) count, voList);
    }
}
